Page({
  data: {
    flag: false
  },

  onLoad(options) {
    wx.showLoading({
      title: '数据正在加载中...',
      mask: true
    })
    const data = wx.getStorageSync('UserData') || {
      class: []
    };
    if (data.class.length == 0) {
      this.setData({flag:false})
    } else {
      this.judgeTags(data.class)
    }
    wx.hideLoading()
  },

  judgeTags(kecheng){
    const colorMap = {
      '汉语言文学': 'red',
      '新闻学': 'yellow',
      '网新': 'blue'
    };
    for (const course of kecheng) {
      if (typeof course !== 'object' || course === null) continue;
      const color = colorMap[course.zhuanye];
      if (color) {
        course.judgeColor = color;
      }
    }
    this.setData({
      class: kecheng,
      flag: true
    })
  },

  GoOnlineClass(e) {
    wx.switchTab({
      url: '/pages/OnlineClass/OnlineClass',
    })
  },
  GoClass(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/OnlineClass/classvideo/classvideo?video_info=' + JSON.stringify(this.data.class[id]),
    })
  },
  Delet(e) {
    var id = e.currentTarget.dataset.id
    console.log(id)
    const data = wx.getStorageSync('UserData') || {
      class: []
    };
    wx.showModal({
      content: '是否取消收藏？',
      cancelText: '否',
      confirmText: '是',
      complete: (res) => {
        if (res.cancel) {
          console.log('nothing')
        }
        if (res.confirm) {
          const index = data.class.findIndex(c => c.url === this.data.class[id].url);
          if (index !== -1) {
            data.class.splice(index, 1);
            wx.setStorageSync('UserData', data);
          }
          const db = wx.cloud.database();
          const user = db.collection('user').where({
            _openid: data._openid
          }).get();
          const userData = {
            class: data.class
          };
          const updateUser = user.then(res => {
            return db.collection('user').doc(res.data[0]._id).update({
              data: userData
            });
          });

          Promise.all([user, updateUser]).then(() => {
            wx.hideLoading();
            wx.showToast({
              title: '处理成功',
              icon: 'success',
              success:res=>{
                this.onLoad()
              }
            });

          }).catch(err => {
            console.error(err);
            wx.hideLoading();
            wx.showToast({
              title: '失败',
              icon: 'none'
            });
          });
        }
      }
    })
  }
})